# -*- coding: utf-8 -*-

import os
import sys
from contextlib import closing
import jinja2
import simplejson
import openerp
from openerp import http
from openerp.http import request
from openerp.modules.registry import RegistryManager
from openerp.addons.wechat.enterprise import WxApi, WxApplication, WxTextResponse, WxNewsResponse, WxArticle, WxLink
from openerp.addons.website_mshop.pools import ModelPool, CursorProxy, common_functions, PageProxy, _slug
from openerp.addons.dftg_weixin.application.application_test import WxAppCropTest
from openerp import tools
SUPERUSER_ID = 1

############################################################################################
# 微信企业号"手机商城"应用消息处理类
# 需要配置wechat.enterprise和wechat.application在data/dftg_corp_weixin.xml文件中
#
class WxAppCWXKF(WxApplication):
    _app_xml_id = 'dftg_weixin.weixin_dftg_assistant_kf'

    # def __init__(self):
    #     if self.is_initialized:
    #         return
    #     self.is_initialized = True
    #     # 取得微信应用配置
    #     db_name = request.session.db
    #     db = RegistryManager.get(db_name)
    #     ir_model_data = openerp.registry(db_name)['ir.model.data']
    #     with closing(db.cursor()) as cr:
    #         application_id = ir_model_data.xmlid_to_res_id(cr, 1, 'dftg_weixin.weixin_dftg_assistant_kf')
    #         if not application_id:
    #             raise Exception('xmlid not found')
    #         wechat_application = openerp.registry(db_name)['wechat.application']
    #         application = wechat_application.browse(cr, SUPERUSER_ID, application_id)
    #         permission_group_ids = application.permission_group_ids
    #         if permission_group_ids:
    #             permission_group = permission_group_ids[0]
    #             self.SECRET = permission_group.secret
    #             self.SECRET_TOKEN = application.callback_token
    #             self.ENCODING_AES_KEY = application.callback_aeskey
    #             self.APP_ID = application.application_id
    #             self.CORP_ID = application.enterprise_id.corp_id.encode("ascii")
    #     self.wxapi = WxApi(self.CORP_ID, self.SECRET)


    def send_to_wx_kf(self, uid, to_uid, message_content, from_uid, context=None):
        # self.pool.get('im_chat.message').browse(cr,uid,)
        # 取得微信应用配置
        db_name = request.session.db
        db = RegistryManager.get(db_name)
        with closing(db.cursor()) as cr:
            contacts_ids = db.get('weixin.contacts').search(cr, SUPERUSER_ID, [('odoo_user_id', 'in', to_uid)])
            from_contacts_id = db.get('weixin.contacts').search(cr, SUPERUSER_ID, [('odoo_user_id', '=', from_uid)])
            if contacts_ids and from_contacts_id:
                message_content_dict = {"sender": {"type": "userid", "id": str(from_contacts_id[0])},
                                        "receiver": {"type": "kf", "id": str(contacts_ids[0])},
                                        "msgtype": "text",
                                        "text": {"content": message_content},
                                        }
                content, errmsg = self.wxapi.send_kf_text(message_content_dict)
                return errmsg
    def odoo_system_to_wixin_kf(self, from_uid, uuid, message_type, message_content):
        db_name = request.session.db
        db = RegistryManager.get(db_name)
        with closing(db.cursor()) as cr:
            session_id =db.get('im_chat.session').search(cr, SUPERUSER_ID,
                                                                 [('uuid', '=', uuid)],
                                                                 order='write_date desc')
            session_id_objs = db.get('im_chat.session').browse(cr, SUPERUSER_ID, session_id)
            user_ids = list(set([user.id for user in session_id_objs.user_ids]) - set([from_uid]))
            if not user_ids:
                user_ids = from_uid
            for users_row in db.get('res.users').browse(cr, SUPERUSER_ID, user_ids):
                if db.get('res.users').has_group(cr, users_row.id, 'base.group_sale_salesman') and from_uid:
                    self.send_to_wx_kf(SUPERUSER_ID, [users_row.id], message_content, from_uid)
    def send_message_media_to_kf(self,image,type):
        db_name = request.session.db
        db = RegistryManager.get(db_name)
        with closing(db.cursor()) as cr:
            contacts_ids = db.get('weixin.contacts').search(cr, SUPERUSER_ID, [('id', '=', int(image.FromUserName))])
            if contacts_ids :
                contacts_obj=db.get('weixin.contacts').browse(cr, SUPERUSER_ID, contacts_ids[0])
                from_contacts_id = db.get('weixin.contacts').search(cr, SUPERUSER_ID, [('odoo_user_id', '=', contacts_obj.odoo_user_id.partner_id.user_id.id)])
                if from_contacts_id:
                    message_content_dict = {"sender": {"type": "userid", "id":str(contacts_ids[0])},
                                            "receiver": {"type": "kf", "id":str(from_contacts_id[0])},
                                            "msgtype": image.MsgType,
                                            type:
                                               {
                                                   "media_id":image.MediaId
                                               }
                                            }
                    content, errmsg = self.wxapi.send_kf_text(message_content_dict)


if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'html'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.dftg_weixin', "html")

env = jinja2.Environment('<%', '%>', '${', '}', '%', loader=loader, autoescape=True)


################################################################
# 企业号手机商城页面微信控制器
#
class WeixinAppAssistantController(http.Controller):
    weixin_app = None

    def __init__(self):
        env.globals['_pool'] = ModelPool()
        env.globals['_cr'] = CursorProxy()
        env.globals['_page'] = PageProxy()
        env.globals['_slug'] = _slug
        env.globals.update(common_functions)
        env.filters['tojson'] = simplejson.dumps
        self.weixin_app = WxAppCWXKF()

    #微信回调入口网址
    @http.route('/weixin/app/test_service', auth='public')
    def weixin(self, **kw):
        result={}
        db = RegistryManager.get(request.session.db)
        try:
            with closing(db.cursor()) as cr:
                result = self.weixin_app.process(request.httprequest.args, request.httprequest.data)
                if isinstance(result, dict):
                    wx_api_sed_text = WxAppCropTest()
                    system_chat_message_dict = wx_api_sed_text.send_odoo_system_message(int(result.get('from_user_id')),
                                                                                        result.get('content'))
                    if result.get('MediaId'):
                        message_content = wx_api_sed_text._generate_image_path(result.get('MediaId'))[0]
                        wx_api_sed_text.wxapi.download_media(result.get('MediaId'),
                                                             wx_api_sed_text._generate_image_path(result.get('MediaId'))[1])
                        if result.get('MsgType')=='image':
                            wx_api_sed_text.wxapi.send_image(result.get('MediaId'), wx_api_sed_text.APP_ID, safe="0",
                              touser=result.get('to_user_id'),
                              media_url=result.get('media_url'))
                            message_type = 'image'
                        elif result.get('MsgType')=='voice':
                            wx_api_sed_text.wxapi.send_voice(result.get('MediaId'), wx_api_sed_text.APP_ID, safe="0",
                                                             touser=result.get('to_user_id'),
                                                             media_url=result.get('media_url'))
                            message_type = 'voice'

                    else:

                        wx_api_sed_text.wxapi.send_text(result.get('content'), wx_api_sed_text.APP_ID, safe="0",
                                                        touser=result.get('to_user_id'))
                        message_content = system_chat_message_dict.get('Content')
                        message_type='message'
                    with closing(db.cursor()) as cr:
                            db.get('im_chat.message').post(cr, SUPERUSER_ID, from_uid=system_chat_message_dict.get('user_id'),
                                                           uuid=system_chat_message_dict.get('uuid'), message_type=message_type,
                                             message_content=message_content)
                else:
                    return result
        except AssertionError, e:
            raise Exception(u'估计是应用没有权限组设置，需要在微信配置->微信企业号里的权限组里添加这个应用，配置后需要重启odoo')
        return result.get('PackageId')


    @http.route('/weixin/editor_image', auth='public')
    def editor_image(self, filename):
        if filename:
            main_direction = tools.config.filestore(request.cr.dbname)
            if (not os.path.isfile(filename)):
                filename = os.path.join(main_direction, filename)

            if (not os.path.isfile(filename)):
                return ''

            with open(filename) as img:
                response = request.make_response(img.read())
                suffix = filename[filename.rfind('.') + 1:]

                response.headers['Content-Type'] = 'image/' + suffix
                response.headers['Content-Disposition'] = 'attachment;filename=%s' % filename.encode('utf-8')

                return response

        return ''